﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using AutoMapper;
using DevWeb.Biztalk.DeploymentSettings.Data.CodeFirst;

using DevWeb.Biztalk.DeploymentSettings.WebUI.Models;
using Microsoft.Ajax.Utilities;
using Microsoft.Practices.Unity;

namespace DevWeb.Biztalk.DeploymentSettings.WebUI.Controllers
{
    public class DefaultSettingsController : BaseController
    {
        
        public ActionResult Index()
        {
            var settings = Context.DefaultSettingParameters.OrderBy(p => p.ParameterName).ToList();

            var model = Mapper.Map<List<DefaultSettingParameter>, List<DefaultSettingsViewModel>>(settings);

            return View(model);
        }


        //
        // GET: /DefaultSettings/Create

        public ActionResult Create()
        {
            DefaultSettingsViewModel model = new DefaultSettingsViewModel() {CreatedDateTime = DateTime.Now};
            return View(model);
        }

        //
        // POST: /DefaultSettings/Create

        [HttpPost]
       // [ValidateInput(false)]
        public ActionResult Create(DefaultSettingsViewModel model)
        {
            try
            {
                if (ModelState.IsValid)

                {
                    var setting = Mapper.Map<DefaultSettingParameter>(model);
                    Context.DefaultSettingParameters.Add(setting);
                    Context.SaveChanges();
                    return RedirectToAction("CreateOrEdit", new {id = setting.Id});
                }
                else
                {
                    return View(model);
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /DefaultSettings/CreateOrEdit/5
        public ActionResult CreateOrEdit(int id)
        {
            var setting = Context.DefaultSettingParameters.Include("DefaultSettingParameterValues").SingleOrDefault(p => p.Id.Equals(id));
            if (setting == null)
            {
                throw new ArgumentException("Setting is unknown");
            }

            var targetenvs = Context.TargetEnvironments.ToList();

            List<ParameterValue> valuelist = new List<ParameterValue>();
            var currentsettings = setting.DefaultSettingParameterValues.ToList();

            foreach (var item in currentsettings)
            {
                var parametervalue = new ParameterValue();
                parametervalue.Environment = item.TargetEnvironment.Name;
                parametervalue.Value = item.Value;
                valuelist.Add(parametervalue);
                targetenvs.Remove(item.TargetEnvironment);
            }

            foreach (var targetEnvironment in targetenvs)
            {
                var newparametervalue = new ParameterValue();
                newparametervalue.Environment = targetEnvironment.Name;
                newparametervalue.Value = string.Empty;
                valuelist.Add(newparametervalue);
            }
            
            DefaultSettingValueModel model = new DefaultSettingValueModel(setting.Id, setting.ParameterName, valuelist, setting.DefaultValue);

            return View(model);
        }

        [HttpPost]
       
        public ActionResult CreateOrEdit(FormCollection collection)
        {
            var id = int.Parse(collection["Id"]);
            var defaultValue = collection["DefaultValue"];
            var defaultparameter =
                Context.DefaultSettingParameters.Include("DefaultSettingParameterValues").SingleOrDefault(p => p.Id.Equals(id));

            
            
            if (defaultparameter==null)
                throw new ArgumentException("DefaultSettingParameter is not found");
            defaultparameter.DefaultValue = defaultValue;
            foreach (var targetEnvironment in Context.TargetEnvironments)
            {
                string newvalue = collection[targetEnvironment.Name];
                var currentvalues =
                    defaultparameter.DefaultSettingParameterValues.SingleOrDefault(
                        p => p.TargetEnvironmentId.Equals(targetEnvironment.Id));
                if (currentvalues!=null)
                {
                   
                    currentvalues.Value = newvalue;
                    currentvalues.CreateDateTime = DateTime.Now;

                }
                else
                {
                    var value = new DefaultSettingParameterValue() { CreateDateTime = DateTime.Now };
                    value.TargetEnvironment = targetEnvironment;
                    value.TargetEnvironmentId = targetEnvironment.Id;
                    value.DefaultSettingParameter = defaultparameter;
                    value.DefaultSettingParameterId = defaultparameter.Id;
                    value.Value = newvalue;
                    defaultparameter.DefaultSettingParameterValues.Add(value);
                }
            }
            Context.SaveChanges();

            return RedirectToAction("Index");
        }

       

        public ActionResult Delete(int id)
        {
            var setting = Context.DefaultSettingParameters.FirstOrDefault(p => p.Id.Equals(id));

           

            var model = Mapper.Map<DefaultSettingsViewModel>(setting);

            return View(model);
        }

        //
        // POST: /DefaultSettings/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, DefaultSettingsViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var setting = Context.DefaultSettingParameters.SingleOrDefault(p => p.Id.Equals(id));

                    
                    Context.DefaultSettingParameters.Remove(setting);
                    Context.SaveChanges();
                }
            }
            catch
            {
                return View();
            }

            return RedirectToAction("Index");
        }
    }
}